<?php
// +----------------------------------------------------------------------
// | Description: 保有
// +----------------------------------------------------------------------
// | Author: zl
// +----------------------------------------------------------------------

namespace app\crm\controller;

use app\admin\controller\ApiCommon;
use app\admin\model\PersonModel;
use app\admin\model\ShopModel;
use app\crm\model\BalanceLog;
use app\crm\model\Setting;
use app\crm\model\SettingCategory;
use app\crm\model\Service;
use app\crm\model\ReturnVist;
use app\crm\model\ReturnVistT;
use app\crm\model\Customer as CustomerModel;
use app\crm\model\ShopRetention as ShopRetentionModel;
use app\crm\model\TransferShop;
use app\mini\model\SysModelMini;
use app\crm\model\CustomerConfig as CustomerConfigModel;
use app\crm\model\CustomerGrade as CustomerGradeModel;
use app\mini\model\SysModelMiniCustomer;
use think\response\Json;
use think\facade\Db;
use Kingdee\Kingdee;

use chillerlan\QRCode\QRCode;
use chillerlan\QRCode\QROptions;

class ShopRetention extends ApiCommon
{
    protected $customerModel;
    protected $customerConfigModel;
    
    /**
     * 用于判断权限
     * @permission 无限制
     * @allow 登录用户可访问
     * @other 其他根据系统设置
     **/
    public function initialize()
    {
        $action = [
            'permission' => ['house_list','setcustomerage','setzycustomer','dsmonth','setmonth'],
            'allow' => ['users', 'info']
        ];
        event('CheckAuth',$action);
        $request = $this->request;
        $a = strtolower($request->action());

        $this->customerModel = new CustomerModel();
        $this->customerConfigModel = new CustomerConfigModel();
        if (!in_array($a, $action['permission'])) {
            parent::initialize();
        }
    }
    
    //查询权限
    public function getAdminLevel(ShopRetentionModel $shopRetentionModel): Json
	{
	    $shopIds = $this->getCommonShopIdsCollectByUserType();
	    if(empty($shopIds))
	    {
	        $data['admin_level'] = 3;
	    }elseif(!empty($shopIds) &&count($shopIds) > 1)
	    {
	        $data['admin_level'] = 2;
	    }elseif(!empty($shopIds) && count($shopIds) == 1)
	    {
	        $data['admin_level'] = 1;
	    }
	    return resultArray(['data' => $data]);
	}
    
    
    //数据 - 保有数据报表
    public function getRetentionList(ShopRetentionModel $shopRetentionModel): Json
	{
	    $shopIds = $this->getCommonShopIdsCollectByUserType();
	    $this->param['user_id']    = $this->userInfo['id'];
	    $this->param['shopIds']    = $shopIds;
	    $is_export = $this->param['is_export'] ?? 0;
	    $is_export_admin = $this->param['is_export_admin'] ?? 0;
	    
	    $data = $shopRetentionModel->retentionList($this->param);
	    if (!$data)
	    {
	        return resultArray(['error' => $shopRetentionModel->getError()]);
	    }
	   // var_dump($data['list']);die;
	    //导出excel
        if($is_export == 1 || $is_export_admin == 1)
        {
            if($is_export_admin == 1)
            {
                $this->param['admin_level'] = 2;
            }
            $excelName = "保有顾客列表";
            
            // 定义公共的 $callName 部分
            $commonCallName = [
                'level' => '客户等级',
                'all_baoyou' => '客户保有量(总)',
                'total_count' => '客户数量',
                'retained_count' => '客户保有数',
                'lost_count' => '客户流失数',
                'retention_rate' => '客户保有率',
                'lost_warning' => '客户流失预警数',
                'reflux_count' =>  '客户回流数',
                'lost_warning_rate' => '客户流失预警率',
                'year_amount' => '年消费值',
                'mz_amount' => '门诊消费',
                'md_amount' => '门店消费',
                'gongxian' => '门店贡献值',
            ];
            
            // 根据不同权限级别合并特定的键值对
            switch ($this->param['admin_level'])
            {
                case 3:
                    $callName = array_merge([
                        'market_name' => '市场名称'
                    ], $commonCallName);
                    break;
                case 2:
                    $callName = array_merge([
                        'market_name' => '市场名称',
                        'shop_name' => '门店名称'
                    ], $commonCallName);
                    break;
                default:
                    $callName = array_merge([
                        'shop_name' => '门店名称',
                    ], $commonCallName);
                    break;
            }
            $downUrl = exportExcelData($excelName,$callName,$data['list'],'xlsx',1);
            return resultArray(['data' =>['url' => 'http://'.$_SERVER['HTTP_HOST'].$downUrl],'error' => '获取成功']);
            exit;
        }
        
	    return resultArray(['data' => $data]);
	}
	
	//数据 - 保有数据报表 - ABCDE客户明细
	public function getCustomerDetails(ShopRetentionModel $shopRetentionModel): Json
	{
	    $shopIds = $this->getCommonShopIdsCollectByUserType();
	    $this->param['user_id']    = $this->userInfo['id'];
	    $is_export = $this->param['is_export'] ?? 0;
	    $this->param['shopIds']    = $shopIds;

	    $data = $shopRetentionModel->customerDetails($this->param);
	    if (!$data) {
	        return resultArray(['error' => $shopRetentionModel->getError()]);
	    }
	    
	    if($is_export == 1)
        {
            $excelName = "保有数据顾客详情列表";
            
            $callName = [
                'shop_name' => '门店名称',
                'customer_name' => '姓名',
                'telephone' => '手机号',
                'sex' => '性别',
                'source_name' => '来源',
                'yucun' => '客户预存',
                'baoliu' => '保有/流失',
                'year_amount' => '年度消费金额',
                'mz_amount' => '门诊消费金额',
                'md_amount' => '门店消费金额',
                'gongxian' => '门店贡献值',
                'last_xiaofei' => '最新消费时间',
                'last_hexiao' => '最新核销时间',
                'cj_time' => '成交时间',
                'nurse_name' => '护理师',
                'last_kftime' => '最新回访时间',
                'warning_time' => '流失预警日期',
            ];
            
            $downUrl = exportExcelData($excelName,$callName,$data['list']['data'],'xlsx',1);
            return resultArray(['data' =>['url' => 'http://'.$_SERVER['HTTP_HOST'].$downUrl],'error' => '获取成功']);
            exit;
        }
	    
	    return resultArray(['data' => $data]);
	}
    
    
    public function getTelephone(): Json
    {
        // 从参数中获取电话号码
        $id = $this->param['id'] ?? null;
        if (!$id) {
            return resultArray(['error' => '缺少用户ID参数']);
        }
        
        $telephone = Db::name('customer')->where('id',$id)->value('telephone');
        
        // 检查电话号码是否有效
        if (!$telephone) {
            return resultArray(['error' => '未找到有效的电话号码']);
        }
        
        // 返回电话号码
        return resultArray(['data' => $telephone]);

        // // 构建符合拨号跳转的二维码内容
        // $qrContent = 'tel:' . $telephone;

        // // 配置二维码选项
        // $options = new QROptions([
        //     'version' => 5, // 二维码版本
        //     'outputType' => QRCode::OUTPUT_IMAGE_PNG, // 输出类型为 PNG 图片
        //     'eccLevel' => QRCode::ECC_L, // 纠错级别
        //     'imageBase64' => false, // 不使用 Base64 编码
        // ]);

        // try {
        //     // 生成二维码
        //     $qrcode = (new QRCode($options))->render($qrContent);
        //     // 对二维码图片数据进行 Base64 编码
        //     $base64QrCode = base64_encode($qrcode);

        //     return resultArray(['data' => 'data:image/png;base64,'. $base64QrCode]);
            
        //     // 设置响应头，指定输出为 PNG 图片
        //     // header('Content-type: image/png');
        //     // // 输出二维码图片
        //     // echo $qrcode;die;
            
        // } catch (Exception $e) {
        //     return resultArray(['error' => '生成二维码时出错: '. $e->getMessage()]);
        // }
    }
    
    
    
    
    
    
    
    
    
    
}